package com.nnfe.fyd.feature.main;

import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.nnfe.fyd.R;
import com.nnfe.fyd.ShareKey;
import com.nnfe.fyd.base.WebViewActivity;
import com.nnfe.fyd.bean.HttpResult;
import com.nnfe.fyd.feature.login.LoginActivity;
import com.nnfe.fyd.http.CallbackImpl;
import com.nnfe.fyd.http.Url;
import com.nnfe.fyd.utils.DialogUtil;
import com.nnfe.fyd.utils.ImageUtil;
import com.nnfe.fyd.utils.LogUtil;
import com.nnfe.fyd.utils.PhoneUtil;
import com.nnfe.fyd.utils.SharePrefUtil;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.utils.DiskCacheUtils;
import com.nostra13.universalimageloader.utils.MemoryCacheUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Response;

import static android.app.Activity.RESULT_OK;

/**
 * ----------------------------------
 * Created by xyd on 2017/3/15.
 * <p/>
 * 描  述： 首页  我的页面
 * <p/>
 * 修订历史:
 * ----------------------------------
 */

public class MainFragmentTabThree extends MainFragmentBase {
    @Bind(R.id.iv_head)
    ImageView ivHead;
    @Bind(R.id.tv_phone_num)
    TextView tvPhoneNum;
    @Bind(R.id.text_login)
    TextView tvLogin;

    @Override
    public Object getTitleString() {
        return "我的";
    }

    @Override
    public int getContentView() {
        return R.layout.fragment_main_tab_three;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        String num = SharePrefUtil.getString(mContext, ShareKey.Mobile);
        if (SharePrefUtil.getBoolean(mContext,ShareKey.isLogin,false)) {
            tvPhoneNum.setText(num.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
            tvLogin.setText("退出");
        } else {
            tvPhoneNum.setText("未登录");
            tvLogin.setText("登录");
        }

        if (SharePrefUtil.getBoolean(mContext,ShareKey.isLogin,false)){
            getHeadImage();
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    final private int REQUEST_CODE_ASK_PERMISSIONS = 123;
    @OnClick({R.id.iv_head, R.id.tv_phone_num, R.id.text_login, R.id.search_one, R.id.search_two, R.id.search_three})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_head:
            case R.id.tv_phone_num:
                if (checkLogin()) {
                    // 6.0以上做 permission 判断

                    if (Build.VERSION.SDK_INT >= 23){
                        int has_write_permission = mContext.checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
                        if (has_write_permission != PackageManager.PERMISSION_GRANTED) {
                            mContext.requestPermissions(new String[] {android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                    REQUEST_CODE_ASK_PERMISSIONS);
                            return;
                        }
                    }
                    changeHeadImage("上传头像");
                } else {
                    LoginActivity.lauch(mContext, LoginActivity.TYPE_LOGIN);
                }
                break;
            case R.id.text_login:
                if (checkLogin()) {
                    tvLogin.setText("登录");
                    tvPhoneNum.setText("未登录");
                    if (ImageLoader.getInstance().getLoadingUriForView(ivHead) != null){
                        ImageLoader.getInstance().cancelDisplayTask(ivHead);
                    }
                    ImageUtil.displayRoundImage("drawable://"+R.drawable.my_icon, ivHead, PhoneUtil.dip2px(60), R.drawable.my_icon);
                    SharePrefUtil.clear(mContext);

                } else {
                    LoginActivity.lauch(mContext, LoginActivity.TYPE_LOGIN);
                }
                break;
            case R.id.search_one:
                WebViewActivity.lauch(mContext, "资料清单", Url.URL_inquiry_list);

                break;
            case R.id.search_two:
                WebViewActivity.lauch(mContext, "流程指南", Url.URL_inquiry_procedure);

                break;
            case R.id.search_three:
                WebViewActivity.lauch(mContext,"关于718金融",Url.URL_about718);
//                if (checkLogin()) {
//                    MyInquiryActivity.lauch(mContext);
//                } else {
//                    ToastUtil.showToast("请先登录");
//                }

                break;
        }
    }

    private static final int PICK_FROM_CAMERA = 1;
    private static final int CROP_FROM_CAMERA = 2;
    private static final int PICK_FROM_FILE = 3;
    private Uri imgUri;

    /**
     * 对头像的操作
     *
     * @param actionName dialog的title
     */
    private void changeHeadImage(String actionName) {

        DialogUtil.showAlertDialog(mContext, actionName, "请选择头像", "相册", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 方式1，直接打开图库，只能选择图库的图片
                Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                // 方式2，会先让用户选择接收到该请求的APP，可以从文件系统直接选取图片
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
                intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                // 设置数据类型  要限制上传到服务器的图片类型时可以直接写如："image/jpeg 、 image/png等的类型"
                intent.setType("image/*");
                startActivityForResult(i, PICK_FROM_FILE);

            }
        }, "拍照", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                imgUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                        "avatar_" + String.valueOf(System.currentTimeMillis())
                                + ".png"));
                Log.e("xyd", "拍照保存的地址是：" + imgUri);
                // 下面这句指定调用相机拍照后的照片存储的路径，这样通过这个uri就可以得到这个照片了
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
                startActivityForResult(intent, PICK_FROM_CAMERA);

            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        LogUtil.e("xyd", "resultCode:::" + resultCode + "  requestCode:::" + requestCode);
        if (resultCode != RESULT_OK) {

            return;
        }
        switch (requestCode) {
            case PICK_FROM_CAMERA:
                doCrop(ivHead.getWidth(), ivHead.getHeight());
                break;
            case PICK_FROM_FILE:
                imgUri = data.getData();
                Log.e("xyd", "头像设置的大小是：" + ivHead.getWidth() + "+" + ivHead.getHeight());
                Log.e("xyd", "选择的相册中照片地址是：" + imgUri);
                doCrop(ivHead.getWidth(), ivHead.getHeight());
                break;
            case CROP_FROM_CAMERA:
                if (null != data) {
                    setAndUploadCropImg(data);
                }
                break;
        }
    }


    /**
     * 设置头像
     *
     * @param picdata
     */
    private void setAndUploadCropImg(Intent picdata) {
        Bundle bundle = picdata.getExtras();
        if (null != bundle) {
            Bitmap mBitmap = bundle.getParcelable("data");
            String imageUrl = ImageUtil.savePhoto(mContext, mBitmap, false);
            LogUtil.e("xyd", "imageurl路径是" + imageUrl);
            File file = new File(imageUrl);
            final RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            Call<HttpResult<String>> call = service.uploadHeadImage(SharePrefUtil.getString(mContext, ShareKey.UserId, ""), requestBody);
            call.enqueue(new CallbackImpl<String>() {
                @Override
                public void responseSuccess(Call<HttpResult<String>> call, Response<HttpResult<String>> response) {
                    getHeadImage();
                }
            });


        }
    }


    /**
     * 获取头像地址并设置
     */
    private void getHeadImage() {
        String userid = SharePrefUtil.getString(mContext, ShareKey.UserId, "");
        Call<HttpResult<String>> call = service.getHeadImg(userid, System.currentTimeMillis() + "");
        call.enqueue(new CallbackImpl<String>() {
            @Override
            public void responseSuccess(Call<HttpResult<String>> call, Response<HttpResult<String>> response) {
                if (response.body().status == 0 && response.body().data != null) {
                    LogUtil.e("xyd", "头像的地址是:" + response.body().data);
                    String url = response.body().data;
                    SharePrefUtil.saveString(mContext, ShareKey.Head_Url, url);
                    DiskCacheUtils.removeFromCache(url, ImageLoader.getInstance().getDiskCache());
                    MemoryCacheUtils.removeFromCache(url, ImageLoader.getInstance().getMemoryCache());
                    ImageUtil.displayRoundImage(url, ivHead, PhoneUtil.dip2px(60), R.drawable.my_icon);
                }
            }
        });

    }


    /**
     * 裁剪图片
     */
    private void doCrop(int outputX_PX, int outputY_PX) {

        //
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setType("image/*");
        List<ResolveInfo> list = mContext.getPackageManager().queryIntentActivities(intent, 0);
        int size = list.size();

        if (size == 0) {
            //Toast.makeText(this, "can't find crop app", Toast.LENGTH_SHORT).show();
            return;
        } else {
            intent.setData(imgUri);
            intent.putExtra("outputX", outputX_PX);
            intent.putExtra("outputY", outputY_PX);
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            intent.putExtra("scale", true);
            intent.putExtra("return-data", true);

            // only one
            if (size == 1) {
                Intent i = new Intent(intent);
                ResolveInfo res = list.get(0);
                i.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
                startActivityForResult(i, CROP_FROM_CAMERA);
            }
        }
    }

    /**
     * 是否满足登录条件
     *
     * @return
     */
    private boolean checkLogin() {
        String token = SharePrefUtil.getString(mContext, ShareKey.Token);
        if (TextUtils.isEmpty(token)) {
            return false;
        } else {
            return true;
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(String str) {

    }
}
